package com.yonyou.crm.cum.customer.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yonyou.crm.bpub.list.entity.AppListVO;
import com.yonyou.crm.bpub.list.entity.AppListValueVO;
import com.yonyou.crm.common.biz.service.BaseBizServiceImpl;
import com.yonyou.crm.common.field.handler.FieldRelationHandler;
import com.yonyou.crm.common.field.relation.FieldRelation;
import com.yonyou.crm.common.field.relation.RefFieldRelation;
import com.yonyou.crm.common.login.context.LoginContextConstant;
import com.yonyou.crm.common.model.util.ModelUtil;
import com.yonyou.crm.common.page.entity.Page;
import com.yonyou.crm.cum.customer.dynamic.DymCumRelUserAdd;
import com.yonyou.crm.cum.customer.dynamic.DymCumRelUserDelete;
import com.yonyou.crm.cum.customer.entity.CustomerRelusersDO;
import com.yonyou.crm.cum.customer.entity.CustomerRelusersVO;
import com.yonyou.crm.cum.customer.entity.CustomerSalesVO;
import com.yonyou.crm.cum.customer.entity.CustomerVO;
import com.yonyou.crm.sys.dynamic.impl.DynamicServiceImpl;
import com.yonyou.crm.sys.org.service.SysOrgBizServiceImpl;
import com.yonyou.crm.sys.user.entity.UserVO;
import com.yonyou.crm.sys.user.service.UserBizServiceImpl;
import com.yonyou.iuap.context.InvocationInfoProxy;

@Service
public class CustomerRelusersBizServiceImpl extends
        BaseBizServiceImpl<CustomerRelusersDO> {

    @Autowired
    private SysOrgBizServiceImpl orgService;

    @Autowired
    private UserBizServiceImpl userService;

    @Autowired
    private DynamicServiceImpl dynamicService;
    @Autowired
    private CustomerBizServiceImpl cumService;
    @Autowired
    private CustomerSalesBizServiceImpl saleService;

    /**
     * 获取app参与人相关列表
     *
     * @param customerId
     * @return
     */
    public Map<String, Object> getRelUserForcusRel(Long customerId, Integer limit) {
        Map<String, Object> relUserMap = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        param.put("customerId", customerId);
        param.put("tenant_id", new Long(InvocationInfoProxy.getTenantid()));
        List<CustomerRelusersDO>  relUserListForNum = dao.selectVoList(CustomerRelusersDO.class, "getRelUserForCusRelate", param);
        param.put("limit", limit);
        List<CustomerRelusersDO> relUserList = dao.selectVoList(CustomerRelusersDO.class, "getRelUserForCusRelate", param);
        List<CustomerRelusersVO> relVOS = ModelUtil.copyModelList(relUserList, CustomerRelusersVO.class);
        transRelusers(relVOS);
        relUserMap.put("type", "customerReluser");     //相关对象类型，如：contact
        relUserMap.put("name", "参与人");             //相关对象名称，如：联系人
        relUserMap.put("num", relUserListForNum == null ? 0 : relUserListForNum.size());   //相关对象数量

        Long userId = new Long(InvocationInfoProxy.getParameter("id"));
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("cumId", customerId);
        paramMap.put("tenantId", new Long(InvocationInfoProxy.getTenantid()));
        paramMap.put("orgId", new Long(InvocationInfoProxy.getParameter("orgid")));
        List<CustomerSalesVO> saleList = saleService.selectByCustomer(paramMap);

        if (saleList != null) {
            boolean isOnwer = false;
            boolean isManager = false;
            for (int i = 0; i < saleList.size(); i++) {
                CustomerSalesVO saleInfo = saleList.get(i);
                if (userId.toString().equals(saleInfo.getOwnerUserId().toString())) {
                    isOnwer = true;
                }
                Long deptId = saleInfo.getOwnerDeptId();
                List<String> managerIdList = userService.getSMIdListByDeptId(deptId);
                if (managerIdList != null && managerIdList.contains(userId.toString())) {
                    isManager = true;
                }
            }
            if (isManager || isOnwer) { //只有负责员工 或者 销售经理 才可以添加
                relUserMap.put("isnew", "Y");
            }

        }
        relUserMap.put("isdel", "Y");    //证明这个相关对象可以移除
        //具体相关对象的行数据显示（参考获取列表接口实现，具体见下方描述

        List<AppListVO> detaillist = new ArrayList<AppListVO>();

        if (relVOS != null && relVOS.size() > 0) {
            for (int i = 0; i < relUserList.size(); i++) {
                CustomerRelusersVO cusRelUserVO = relVOS.get(i);
                AppListVO listVO = tranVoToAppListVO(cusRelUserVO);
                detaillist.add(listVO);
            }

            relUserMap.put("detaillist", detaillist);
        }

        return relUserMap;
    }

    /**
     * 将数据转化为App列表数据
     *
     * @param cusRelUserVO
     * @return
     */
    public AppListVO tranVoToAppListVO(CustomerRelusersVO cusRelUserVO) {
        AppListVO listVO = new AppListVO();
        listVO.setId(cusRelUserVO.getId());


        List<List<AppListValueVO>> valueList = new ArrayList<>();

        List<AppListValueVO> colList = new ArrayList<>();

        AppListValueVO listValue;

        listValue = new AppListValueVO();
        listValue.setItemkey("id");
        listValue.setDisplayvalue(cusRelUserVO.getUserId());
        colList.add(listValue);

        listValue = new AppListValueVO();
        listValue.setItemkey("name");
        listValue.setDisplayvalue(cusRelUserVO.getUserName());
        colList.add(listValue);

        valueList.add(colList);

        listVO.setValuelist(valueList);
        return listVO;
    }

    /**
     * 获取参与人列表
     *
     * @param page
     * @param paramMap
     * @return
     */
    public Page<CustomerRelusersVO> getList(Page<CustomerRelusersVO> page,
                                            Map<String, Object> paramMap) {
        Page<CustomerRelusersDO> relusersPage = null;
        if (paramMap != null) {
            relusersPage = super.pageSelect(CustomerRelusersDO.class, page,
                    paramMap.keySet().toArray(new String[0]), paramMap.values()
                            .toArray(new Object[0]));
        } else {
            relusersPage = super.pageSelect(CustomerRelusersDO.class, page,
                    null, null);
        }
        Page<CustomerRelusersVO> result = ModelUtil.copyPageModel(relusersPage, CustomerRelusersVO.class);
        transRelusers(result.getData());
        return result;
    }


    private List<CustomerRelusersVO> transRelusers(List<CustomerRelusersVO> list) {
        List<FieldRelation<CustomerRelusersVO>> relations = new ArrayList<FieldRelation<CustomerRelusersVO>>();
        relations.add(new RefFieldRelation<CustomerRelusersVO>(
                CustomerRelusersVO.class, "deptId",
                new String[]{"deptName"}, orgService, "selectFieldsByIds"));
        relations.add(new RefFieldRelation<CustomerRelusersVO>(
                CustomerRelusersVO.class, "userId",
                new String[]{"userName"}, userService, "selectFieldsByIds"));
        new FieldRelationHandler<CustomerRelusersVO>().handler(list, relations);
        return list;
    }

    /**
     * 新增参与人
     *
     * @param vo
     * @return
     */
    public CustomerRelusersVO insert(CustomerRelusersVO vo) {
        int isReluser = isReluser(vo);
        if (isReluser >= 1) {
            return null;
        } else {
            //插入动态
            UserVO user = getCurrentUser();
            CustomerVO cumVo = cumService.getDetail(vo.getCumId());
            List<CustomerRelusersVO> refuserList = getCumRelusers(vo.getCumId());
            Long[] idArr = new Long[]{};
            List<Long> idList = new ArrayList<Long>();
            idList.add(vo.getUserId());
            if (refuserList != null && refuserList.size() > 0) {
                for (CustomerRelusersVO relUser : refuserList) {
                    idList.add(relUser.getUserId());
                }
            }
            if (idList != null && idList.size() > 0) {
                idArr = idList.toArray(new Long[0]);
            }
            //插入参与人数据
            CustomerRelusersDO relDO = super.saveVO(ModelUtil.copyModel(vo, CustomerRelusersDO.class));
            CustomerRelusersVO relVo = ModelUtil.copyModel(relDO, CustomerRelusersVO.class);
            transRelusers(Arrays.asList(relVo));
            DymCumRelUserAdd relAdd = new DymCumRelUserAdd(dynamicService, user, relVo, cumVo, idArr);
            relAdd.execute();
            return relVo;
        }
    }

    @Override
    public void beforeSaveVO(CustomerRelusersDO relDO) {
        super.beforeSaveVO(relDO);
        String userIdStr = InvocationInfoProxy.getParameter("id");// 登录用户id
        Long userId = Long.parseLong(userIdStr);
        Date date = new Date();

        Long reluserId = relDO.getUserId();// 参与人id
        UserVO user = userService.getDetail(reluserId);

        relDO.setOrgId(user.getOrgId());
        relDO.setDeptId(user.getDeptId());
        relDO.setUserId(reluserId);
        relDO.setCreatedUserId(userId);
        relDO.setCreatedTime(date);
    }

    /**
     * 判断是否存在此参与人
     *
     * @param vo
     * @return
     */
    public int isReluser(CustomerRelusersVO vo) {
        String orgIdStr = InvocationInfoProxy.getParameter("orgid");// 所属公司
        String tenantIdStr = InvocationInfoProxy.getTenantid();
        Long orgId = Long.parseLong(orgIdStr);
        Long tenantId = Long.parseLong(tenantIdStr);
        Map<String, Object> paramMap = new HashedMap<String, Object>();
        paramMap.put("userId", vo.getUserId());
        paramMap.put("orgId", orgId);
        paramMap.put("tenantId", tenantId);
        paramMap.put("cumId", vo.getCumId());
        int count = dao.countAll(CustomerRelusersDO.class, "isReluser",
                paramMap);
        if (count > 0) {
            return 1;
        }
        return 0;
    }

    /**
     * 删除参与人
     */
    public int delete(Long id) {
        //插入动态
        UserVO user = getCurrentUser();
        CustomerRelusersDO relDo = dao.getById(CustomerRelusersDO.class, id);
        CustomerRelusersVO vo = ModelUtil.copyModel(relDo, CustomerRelusersVO.class);
        transRelusers(Arrays.asList(vo));
        CustomerVO cumVo = cumService.getDetail(vo.getCumId());
        List<CustomerRelusersVO> refuserList = getCumRelusers(vo.getCumId());
        Long[] idArr = new Long[]{};
        if (refuserList != null && refuserList.size() > 0) {
            List<Long> idList = new ArrayList<Long>();
            for (CustomerRelusersVO relUser : refuserList) {
                if (!relUser.getId().equals(id)) {
                    idList.add(relUser.getUserId());
                }
            }
            if (idList != null && idList.size() > 0) {
                idArr = idList.toArray(new Long[0]);
            }
        }
        DymCumRelUserDelete relDelete = new DymCumRelUserDelete(dynamicService, user, vo, cumVo, idArr);
        relDelete.execute();
        relDo.setId(id);
        return super.deleteVO(relDo);
    }

    /**
     * 根据客户ID获取客户的参与人列表
     *
     * @param cumId
     * @return
     */
    public List<CustomerRelusersVO> getCumRelusers(Long cumId) {
        Map<String, Object> param = new HashedMap<String, Object>();
        param.put("cumId", cumId);
        List<CustomerRelusersDO> doList = dao.selectVoList(CustomerRelusersDO.class, "getCumRefuserList", param);
        return ModelUtil.copyModelList(doList, CustomerRelusersVO.class);
    }

    /**
     * 获取当前登录用户
     *
     * @return
     */
    private UserVO getCurrentUser() {
        Long curUser = Long.parseLong(InvocationInfoProxy.getParameter(LoginContextConstant.UserId));
        UserVO user = userService.getDetail(curUser);
        return user;
    }


}
